package com.schoolcloud.front.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.schoolcloud.common.model.NotificationRequest;
import com.schoolcloud.common.model.PageDTO;
import com.schoolcloud.common.model.UserInfo;
import com.schoolcloud.common.util.UserContext;
import com.schoolcloud.front.entity.FroUser;
import com.schoolcloud.front.entity.NotificationTemplates;
import com.schoolcloud.front.entity.Notifications;
import com.schoolcloud.front.query.NotificationQuery;
import com.schoolcloud.front.service.FroUserService;
import com.schoolcloud.front.service.NotificationTemplatesService;
import com.schoolcloud.front.service.NotificationsService;
import com.schoolcloud.front.mapper.NotificationsMapper;
import com.schoolcolud.daomybatisplus.dto.MpPageUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author hongmizfb
 * @description 针对表【notifications(通知表)】的数据库操作Service实现
 * @createDate 2025-08-16 15:52:05
 */
@Service
@RequiredArgsConstructor
public class NotificationsServiceImpl extends ServiceImpl<NotificationsMapper, Notifications>
        implements NotificationsService {
    private final NotificationTemplatesService notificationTemplatesService;

    private final FroUserService froUserService;

    /**
     * 模板解析工具方法
     *
     * @param template  模板字符串
     * @param variables 变量键值对
     * @return 解析后的字符串
     */
    private static String parseTemplate(String template, Map<String, String> variables) {
        if (StrUtil.isBlank(template) || CollUtil.isEmpty(variables)) {
            return template;
        }
        // 匹配{{{{{{变量名}}格式的正则表达式
        Pattern pattern = Pattern.compile("\\{\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\}");
        Matcher matcher = pattern.matcher(template);
        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            String varName = matcher.group(1); // 提取变量名
            String varValue = variables.getOrDefault(varName, ""); // 获取变量值，默认空字符串
            // 替换变量并处理特殊字符
            matcher.appendReplacement(result, Matcher.quoteReplacement(varValue));
        }
        matcher.appendTail(result);
        return result.toString();
    }

    @Override
    public Notifications saveNotification(NotificationRequest notificationRequest) {
        Notifications notifications = generateNotification(notificationRequest);
        save(notifications);
        return notifications;
    }

    @Override
    public PageDTO<Notifications> getNotificationPage(NotificationQuery query) {
        Page<Notifications> page = lambdaQuery().page(query.toMpPage());
        return MpPageUtil.of(page, Notifications.class);
    }

    private Notifications generateNotification(NotificationRequest notificationRequest) {
        // 1. 创建通知对象并设置基础属性
        Notifications notification = new Notifications();
        notification.setUserId(notificationRequest.getReceiverId());
        notification.setSenderId(notificationRequest.getSenderId());
        notification.setRelatedId(notificationRequest.getRelatedId());
        notification.setRelatedType(notificationRequest.getRelatedType());
        notification.setType(notificationRequest.getType());
        notification.setIsRead(0); // 默认未读
        notification.setIsDeleted(0); // 默认未删除
        notification.setCreateTime(LocalDateTime.now()); // 设置当前时间为创建时间
        // 2. 获取获取对应的通知模板
        String type = notificationRequest.getType();
        NotificationTemplates template = notificationTemplatesService.getByType(type);
        if (template == null) {
            throw new IllegalArgumentException("未找到类型为[" + type + "]的通知模板");
        }
        // 3. 获取变量映射
        Map<String, String> variables = notificationRequest.getVariables();
        if (variables == null) {
            variables = new HashMap<>();
        }
        Integer senderId = notificationRequest.getSenderId();
        if (senderId != null) {
            FroUser sender = froUserService.getById(senderId);
            variables.put("sender_name", sender.getNickname());//内置变量 sender_name
        }
        // 4. 解析模板并设置标题、内容和链接
        notification.setTitle(parseTemplate(template.getTitleTemplate(), variables));
        notification.setContent(parseTemplate(template.getContentTemplate(), variables));
        notification.setLink(parseTemplate(template.getLinkTemplate(), variables));
        return notification;
    }
}




